package com.csdig.cms.web.admin;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csdig.cms.common.ConstantDefine;
import com.csdig.cms.model.Channel;
import com.csdig.cms.model.Content;
import com.csdig.cms.model.ContentTxt;
import com.csdig.cms.service.ChannelService;
import com.csdig.cms.service.ContentService;
import com.csdig.cms.utils.PageUtils;
import com.csdig.db.model.Pagination;

@Controller
@RequestMapping(value = ConstantDefine.AdminUrl.BASE + "/content")
public class ContentController {

	@Autowired
	private ContentService contentService;

	@Autowired
	private ChannelService channelService;

	@RequestMapping(value = "/{name}View")
	public String list(@PathVariable String name) throws Exception {
		return "content/" + name;
	}

	@RequestMapping(value = "/getArticleList")
	@ResponseBody
	public Map<String, Object> getArticleList(Integer channelPid, Integer page, Integer rows) throws Exception {
		Pagination<Content> pag = contentService.findAllByPid(channelPid, PageUtils.getPageNo(page),
				PageUtils.getPageSize(rows));
		return PageUtils.toMap(pag);
	}

	@RequestMapping(value = "/add")
	public String addContent(HttpServletRequest request, Integer channelPid) throws Exception {
		// 获取到当前channel
		Channel channel = channelService.getById(channelPid);
		request.setAttribute("channel", channel);
		return "content/content";
	}

	@RequestMapping(value = "/edit")
	public String edit(HttpServletRequest request, Integer contentId) throws Exception {
		Content content = contentService.findById(contentId);
		content.setDescription(PageUtils.reservDes(content.getDescription()));
		request.setAttribute("content", content);

		ContentTxt txt = contentService.findTxtById(contentId);
		txt.setTxt(PageUtils.resoleLazyImg(txt.getTxt()));
		request.setAttribute("txt", txt);

		Channel channel = channelService.getById(content.getChannelId());
		request.setAttribute("channel", channel);
		return "content/content";
	}

	@RequestMapping(value = "/save")
	@ResponseBody
	public Map<String, Object> saveContent(Content bean, String content) throws Exception {
		if (bean.getContentId() == null) {
			contentService.saveContent(bean, content);
		} else {
			contentService.updateContent(bean,content);
		}
		Map<String, Object> result = new HashMap<String, Object>();
		return result;
	}
	
	@RequestMapping(value = "/del")
	@ResponseBody
	public Map<String, Object> del(Integer contentId) throws Exception {
		contentService.del(contentId);
		Map<String, Object> result = new HashMap<String, Object>();
		return result;
	}


}
